package liuhe.manager;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Vector;

import org.json.JSONArray;
import org.json.JSONObject;

import liuhe.LiuHe;
import liuhe.http.JiarunHttp;

public class JiarunManager {
	public Vector<JiarunHttp> accounts = new Vector<JiarunHttp>();
	public static JSONArray dataJArray = new JSONArray();
	public static JSONArray oldDataJArray = new JSONArray();
	public void init() {
		File file = new File("account/" + "jiarunaccount.txt");
		if(!file.exists()) {
			System.out.println("[acManager init jiarunaccount.txt] �ļ�������");
			return;
		}
		
		BufferedReader freader = null;
		try {
			freader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
			
			String str = "";
			if ((str = freader.readLine()) != null) {
				JSONArray ja = new JSONArray(str);
				for(int i=0;i<ja.length();i++) {
					JSONObject jb = ja.getJSONObject(i);
					JiarunHttp account = new JiarunHttp();
					if(jb.getBoolean("use")==false) {
						continue;
					}
					account.setLoginParams(jb.getString("address"), jb.getString("account"), jb.getString("password"), jb.getString("searchcode"));
					accounts.add(account);
				}
			}
			LiuHe.mergeManager.addUsefulAccountNum(accounts.size());
			LiuHe.mergeManager.addUsefulAccountNumOld(accounts.size());
			freader.close();
		} catch(FileNotFoundException e) {
			e.printStackTrace();
			return;
		} catch(IOException e) {
			e.printStackTrace();
			return;
		}

	}
	
	public void login() {
		try {
			for(int i = 0; i <accounts.size(); i++ ) {
				
				if(accounts.elementAt(i).getStatusCode() == -1) {
					accounts.elementAt(i).login();
					Thread.sleep(300);
				}
				
				if((accounts.elementAt(i).getStatusCode() == -2) && (System.currentTimeMillis() > accounts.elementAt(i).getCanLoginTime())) {
					accounts.elementAt(i).login();
					Thread.sleep(300);
				}

			}
			
		}catch(Exception e) {
			e.printStackTrace();
		}
	} 
	
	public void getActualData() {
		try {
			dataJArray = new JSONArray();
			for(int i = 0; i<accounts.size();i++) {
				if(accounts.elementAt(i).getStatusCode()==1) {
					accounts.elementAt(i).getActualData();
					Thread.sleep(3000);
				}
			}
			if(dataJArray.length()==accounts.size()) {
				LiuHe.mergeManager.updateJiarunData(dataJArray.toString());
			}
			
		}catch(Exception e) {
			e.printStackTrace();
		}

	}
	
	public void getOldActualData() {
		try {
			oldDataJArray = new JSONArray();
			for(int i = 0; i<accounts.size();i++) {
				if(accounts.elementAt(i).getStatusCode()==1) {
					accounts.elementAt(i).getOldActualData();
					Thread.sleep(3000);
				}
			}
			if(oldDataJArray.length()==accounts.size()) {
				LiuHe.mergeManager.updateJiarunDataOld(oldDataJArray.toString());
			}
			
		}catch(Exception e) {
			e.printStackTrace();
		}

	}
	
}


